package org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.persistence;

import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import org.framework.lazy.cloud.network.heartbeat.common.ChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.ClientProxyRoute;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteContext;
import org.framework.lazy.cloud.network.heartbeat.protocol.route.RouteType;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.entity.LazyNettyClientRouteDO;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.converter.LazyNettyClientRouteConverter;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.client.route.LazyNettyClientRouteRepository;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.infrastructure.entity.LazyNettyClientVirtualRouteDO;
import org.springframework.stereotype.Repository;

import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

import org.wu.framework.core.NormalUsedString;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyUpdateSetValueWrappers;
import org.wu.framework.lazy.orm.database.lambda.stream.wrapper.LazyWrappers;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import jakarta.annotation.Resource;
import org.framework.lazy.cloud.network.heartbeat.server.standalone.domain.model.lazy.netty.client.route.LazyNettyClientRoute;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;
import java.util.List;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
/**
 * describe 客户端代理路由规则 
 *
 * @author Jia wei Wu
 * @date 2025/04/05 09:00 晚上
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence 
 **/
@Repository
public class LazyNettyClientRouteRepositoryImpl  implements  LazyNettyClientRouteRepository {

    @Resource
    LazyLambdaStream lazyLambdaStream;

    /**
     * describe 新增客户端代理路由规则
     *
     * @param lazyNettyClientRoute 新增客户端代理路由规则     
     * @return {@link Result<LazyNettyClientRoute>} 客户端代理路由规则新增后领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyNettyClientRoute> story(LazyNettyClientRoute lazyNettyClientRoute) {
        LazyNettyClientRouteDO lazyNettyClientRouteDO = LazyNettyClientRouteConverter.INSTANCE.fromLazyNettyClientRoute(lazyNettyClientRoute);
        lazyLambdaStream.upsert(lazyNettyClientRouteDO);

        String routeIp = lazyNettyClientRoute.getRouteIp();
        String clientId = lazyNettyClientRoute.getClientId();

        String routePort = NormalUsedString.ASTERISK;
        // 新增虚拟ip映射
        LazyNettyClientVirtualRouteDO lazyNettyClientVirtualRouteDO = new LazyNettyClientVirtualRouteDO();
        lazyNettyClientVirtualRouteDO.setIsDeleted(false);
        lazyNettyClientVirtualRouteDO.setTargetClientId(clientId);
        lazyNettyClientVirtualRouteDO.setVirtualIp(routeIp);
        lazyNettyClientVirtualRouteDO.setVirtualPort(routePort);
        lazyNettyClientVirtualRouteDO.setTargetIp(routeIp);
        lazyNettyClientVirtualRouteDO.setTargetPort(routePort);
        lazyLambdaStream.upsert(lazyNettyClientVirtualRouteDO);

        // 更新服务端路由

        ClientProxyRoute serverProxyClientRoute = new ClientProxyRoute();
        serverProxyClientRoute.setTargetClientId(clientId);
        serverProxyClientRoute.setVirtualIp(routeIp);
        serverProxyClientRoute.setVirtualPort(routePort);
        serverProxyClientRoute.setTargetIp(routeIp);
        serverProxyClientRoute.setTargetPort(routePort);
        serverProxyClientRoute.setRouteType(RouteType.SERVER_PROXY_CLIENT);
        RouteContext.setRoute(serverProxyClientRoute);



        ClientProxyRoute clientProxyRoute = new ClientProxyRoute();
        clientProxyRoute.setTargetClientId(clientId);
        clientProxyRoute.setVirtualIp(routeIp);
        clientProxyRoute.setVirtualPort(routePort);
        clientProxyRoute.setTargetIp(routeIp);
        clientProxyRoute.setTargetPort(routePort);
        clientProxyRoute.setRouteType(RouteType.CLIENT_PROXY_CLIENT);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((channelClientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_CLIENT_ROUTE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增客户端代理路由规则
     *
     * @param lazyNettyClientRouteList 批量新增客户端代理路由规则     
     * @return {@link Result<List<LazyNettyClientRoute>>} 客户端代理路由规则新增后领域对象集合     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<List<LazyNettyClientRoute>> batchStory(List<LazyNettyClientRoute> lazyNettyClientRouteList) {
        List<LazyNettyClientRouteDO> lazyNettyClientRouteDOList = lazyNettyClientRouteList.stream().map(LazyNettyClientRouteConverter.INSTANCE::fromLazyNettyClientRoute).collect(Collectors.toList());
        lazyLambdaStream.upsert(lazyNettyClientRouteDOList);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个客户端代理路由规则
     *
     * @param lazyNettyClientRoute 查询单个客户端代理路由规则     
     * @return {@link Result<LazyNettyClientRoute>} 客户端代理路由规则领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyNettyClientRoute> findOne(LazyNettyClientRoute lazyNettyClientRoute) {
        LazyNettyClientRouteDO lazyNettyClientRouteDO = LazyNettyClientRouteConverter.INSTANCE.fromLazyNettyClientRoute(lazyNettyClientRoute);
        LazyNettyClientRoute lazyNettyClientRouteOne = lazyLambdaStream.selectOne(LazyWrappers.lambdaWrapperBean(lazyNettyClientRouteDO), LazyNettyClientRoute.class);
        return ResultFactory.successOf(lazyNettyClientRouteOne);
    }

    /**
     * describe 查询多个客户端代理路由规则
     *
     * @param lazyNettyClientRoute 查询多个客户端代理路由规则     
     * @return {@link Result<List<LazyNettyClientRoute>>} 客户端代理路由规则领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<List<LazyNettyClientRoute>> findList(LazyNettyClientRoute lazyNettyClientRoute) {
        LazyNettyClientRouteDO lazyNettyClientRouteDO = LazyNettyClientRouteConverter.INSTANCE.fromLazyNettyClientRoute(lazyNettyClientRoute);
        List<LazyNettyClientRoute> lazyNettyClientRouteList = lazyLambdaStream.selectList(LazyWrappers.lambdaWrapperBean(lazyNettyClientRouteDO), LazyNettyClientRoute.class);
        return ResultFactory.successOf(lazyNettyClientRouteList);
    }

    /**
     * describe 分页查询多个客户端代理路由规则
     *
     * @param size 当前页数
     * @param current 当前页
     * @param lazyNettyClientRoute 分页查询多个客户端代理路由规则     
     * @return {@link Result<LazyPage<LazyNettyClientRoute>>} 分页客户端代理路由规则领域对象     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyPage<LazyNettyClientRoute>> findPage(int size,int current,LazyNettyClientRoute lazyNettyClientRoute) {
        LazyNettyClientRouteDO lazyNettyClientRouteDO = LazyNettyClientRouteConverter.INSTANCE.fromLazyNettyClientRoute(lazyNettyClientRoute);
        LazyPage<LazyNettyClientRoute> lazyPage = new LazyPage<>(current,size);
        LazyPage<LazyNettyClientRoute> lazyNettyClientRouteLazyPage = lazyLambdaStream.selectPage(LazyWrappers.lambdaWrapperBean(lazyNettyClientRouteDO),lazyPage, LazyNettyClientRoute.class);
        return ResultFactory.successOf(lazyNettyClientRouteLazyPage);
    }

    /**
     * describe 删除客户端代理路由规则
     *
     * @param lazyNettyClientRoute 删除客户端代理路由规则     
     * @return {@link Result<LazyNettyClientRoute>} 客户端代理路由规则     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<LazyNettyClientRoute> remove(LazyNettyClientRoute lazyNettyClientRoute) {
        lazyLambdaStream.update(LazyUpdateSetValueWrappers.<LazyNettyClientRouteDO>lambdaWrapper()
                        .set(LazyNettyClientRouteDO::getIsDeleted, true),
                LazyWrappers
                        .<LazyNettyClientRouteDO>lambdaWrapper()
                        .eq(LazyNettyClientRouteDO::getId, lazyNettyClientRoute.getId())

        );
        LazyNettyClientRouteDO clientRouteDO = lazyLambdaStream.selectOne(
                LazyWrappers
                        .<LazyNettyClientRouteDO>lambdaWrapper()
                        .eq(LazyNettyClientRouteDO::getId, lazyNettyClientRoute.getId())
        );
        String routeIp = clientRouteDO.getRouteIp();
        String clientId = clientRouteDO.getClientId();
        String routePort=NormalUsedString.ASTERISK;

        ClientProxyRoute clientProxyRoute = new ClientProxyRoute();
        clientProxyRoute.setTargetClientId(clientId);
        clientProxyRoute.setVirtualIp(routeIp);
        clientProxyRoute.setVirtualPort(routePort);
        clientProxyRoute.setTargetIp(routeIp);
        clientProxyRoute.setTargetPort(routePort);
        clientProxyRoute.setRouteType(RouteType.CLIENT_PROXY_CLIENT);
        // 发送所有客户端本地路由刷新
        ChannelContext.getChannels().forEach((channelClientId, channels) -> {
            NettyProxyMsg nettyMsg = new NettyProxyMsg();
            nettyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_SERVER_CLIENT_ROUTE_CLOSE_);
            nettyMsg.setData((JSON.toJSONString(clientProxyRoute)
                    .getBytes(StandardCharsets.UTF_8)));
            // 发送所有客户端ID
            for (Channel channel : channels) {
                channel.writeAndFlush(nettyMsg);
            }
        });
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在客户端代理路由规则
     *
     * @param lazyNettyClientRoute 客户端代理路由规则领域对象     
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在     
     
     * @author Jia wei Wu
     * @date 2025/04/05 09:00 晚上
     **/

    @Override
    public Result<Boolean> exists(LazyNettyClientRoute lazyNettyClientRoute) {
        LazyNettyClientRouteDO lazyNettyClientRouteDO = LazyNettyClientRouteConverter.INSTANCE.fromLazyNettyClientRoute(lazyNettyClientRoute);
        Boolean exists=lazyLambdaStream.exists(LazyWrappers.lambdaWrapperBean(lazyNettyClientRouteDO));
        return ResultFactory.successOf(exists);
    }

}